import {dropOrder, fetchOrder, getOrders} from "../api/chadan.js";
import { getToken, clearToken } from "../api/chadan-login.js";
import { postOrder, checkState } from "../api/order.js";
import config from "../config.js";
import { OrderError } from "../utils/Errors.js";
import whiteList from "../whiteList.js";

let lastTokenTime = 0;

export async function refreshToken() {
  if((Date.now() - lastTokenTime) > config.tokenRefreshInterval) {
    clearToken();
    await getToken();
    lastTokenTime = Date.now();
  }
}

export async function chadanJob() {
  // await checkState();
  const orders = await getOrders();
  if(orders.length === 0) {
    return;
  }
  console.log(`获取到${orders.length}条订单， ${JSON.stringify(orders)}`);
  await Promise.allSettled(orders.map(order => submitOrder(order)));
}

async function submitOrder(order) {
  try {
    console.log(`开始处理订单：${order.id}`);
    const state = checkOrderProfit(order);
    if(!state) {
      console.warn(`订单不符合利润，不接单，${JSON.stringify(order)}`);
      return
    }
    const orderNo = await fetchOrder(order.id);
    order.orderNo = orderNo;
    console.log(`接单成功${order.id},${orderNo}`);
    await postOrder(order);
    console.log(`订单提交到后台成功${order.id},${orderNo}`);
  }catch(err) {
    console.error(`${err.message}，${JSON.stringify(order)}\n${err.stack}`)
    if(err instanceof OrderError) {
      dropOrder(order, err.message).catch(console.error);
    }
  }
}

function checkOrderProfit(order) {
  const totalAmount = order.products.reduce((res, cur) => res + cur.amount, 0);
  if(totalAmount > 1 || order.products.some(v => v.productName.includes('双'))) {
    return order.price / order.officialPrice >= 0.62;
  }
  const productName = order.products[0].productName.replaceAll('·', '');
  const productDetail = order.products[0].productDescription;
  const cupSize = productDetail.split(',')[0].replace('双', '');

  if(cupSize === '中杯') {
    return whiteList.Tall.includes(productName);
  }
  if(cupSize === '大杯') {
    return whiteList.Grande.includes(productName);
  }
  if(cupSize === '超大杯') {
    return whiteList.Venti.includes(productName);
  }
  return true;
}
